package com.my.test.thread;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.concurrent.locks.ReentrantLock;

public class Account {

    private int money = 10000;
    private ReentrantLock reentrantLock = new ReentrantLock();

    public void pickMoney(String name,int money){

        if (money<this.money){
            this.money = this.money - money;
            System.out.println(name+"取钱："+money+",余额为："+this.money);
        } else {
            System.out.println(name+"取钱失败，余额不足");
        }

    }

    //1.同步方法
    /*public synchronized void pickMoney(String name,int money){

        if (money<this.money){
            this.money = this.money - money;
            System.out.println(name+"取钱："+money+",余额为："+this.money);
        } else {
            System.out.println(name+"取钱失败，余额不足");
        }

    }*/

    //2.同步代码块
    /*public void pickMoney(String name,int money){

        //此处省略一万行代码
        synchronized (this){
            if (money<this.money){
                this.money = this.money - money;
                System.out.println(name+"取钱："+money+",余额为："+this.money);
            } else {
                System.out.println(name+"取钱失败，余额不足");
            }
        }
    }*/


    //3.同步锁
    /*public void pickMoney(String name,int money){

        //此处省略一万行代码
        //为什么放到try catch代码块中，据说怕一个线程得到锁后发生异常，锁无法释放
                //但实测，一个线程得到锁后挂掉，另一个线程会得到锁，见demo4
        reentrantLock.lock();
        try {
            if (money<this.money){
                this.money = this.money - money;
                System.out.println(name+"取钱："+money+",余额为："+this.money);
            } else {
                System.out.println(name+"取钱失败，余额不足");
            }
        } catch (Exception e){
            e.printStackTrace();
        } finally {
            reentrantLock.unlock();
        }
    }*/

    //4.得到锁后发生异常，锁会释放
    /*public synchronized void pickMoney(String name,int money){

        try {
            System.out.println(Thread.currentThread().getName()+"*********");
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        try {
            System.out.println(Thread.currentThread().getName()+"+++++++++");
            InputStream inputStream = new FileInputStream("E:\\文件\\CourseDoc\\01-JavaSE.pd");
        } catch (FileNotFoundException e) {
            throw new RuntimeException("+++++++++");
        }

        if (money<this.money){
            this.money = this.money - money;
            System.out.println(name+"取钱："+money+",余额为："+this.money);
        } else {
            System.out.println(name+"取钱失败，余额不足");
        }

    }*/
}
